package com.hly.musicbackground.model.boots.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hly.musicbackground.Final.FictionFinal;
import com.hly.musicbackground.Utils.JsoupBooksUtil;
import com.hly.musicbackground.dao.FictionChapterDao;
import com.hly.musicbackground.dao.FictionDao;
import com.hly.musicbackground.domain.Fiction;
import com.hly.musicbackground.domain.FictionChapter;
import com.hly.musicbackground.domain.FictionClass;
import com.hly.musicbackground.domain.FictionContent;
import com.hly.musicbackground.model.boots.service.FictionChapterService;
import com.hly.musicbackground.model.boots.service.FictionClassService;
import lombok.RequiredArgsConstructor;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 笔趣阁
 * http://www.fyhuabo.com/
 * */

@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class FictionDocumentWwwFyhuaboCom {

    private final FictionClassService fictionClassService;

    private final FictionDao fictionDao;

    private final String baseUrl = "http://www.fyhuabo.com";

    public List<Fiction> searchDomToObject(Document document) {
        Elements bookbox = document.select(".txt-list li");
        ArrayList<Fiction> fictions = new ArrayList<>();
        bookbox.stream().forEach(e -> {
            String category = e.select(".s1 b").text();
            if (!"作品分类".equals(category)){

                String name = e.select(".s2 a").text();

                String url = e.select(".s2 a").attr("href");

                String author = e.select(".s4").text();

                Fiction one = fictionDao.selectOne(new
                        LambdaQueryWrapper<Fiction>().eq(Fiction::getFictionName, name)
                        .eq(Fiction::getFictionAuthor, author));


                if (one == null){
                    Document doc = JsoupBooksUtil.getDoc(baseUrl + url);
                    Fiction fiction = DocumentToFictionDetail(doc);
                    fictions.add(fiction);
                }else if (one.getAbnormal() == FictionFinal.abnormal_ok){
                    fictions.add(one);
                }
            }
        });
        return fictions;
    }

    public Fiction DocumentToFictionDetail(Document document){

        //String num = document.select("div.hits span").get(0)
        //        .text()
        //        .replace(",", "")
        //        .replace("字", "");

        String url = document.select("meta[property=og:novel:read_url]")
                .attr("content");

        String name = document.select("meta[property=og:novel:book_name]")
                .attr("content");

        String description = document.select("meta[property=og:description]")
                .attr("content");

        String fictionClassName = document.select("meta[property=og:novel:category]")
                .attr("content");

        String updateTime = document.select("meta[property=og:novel:update_time]")
                .attr("content");

        String status = document.select("meta[property=og:novel:status]")
                .attr("content");

        String http = "http://www.biquge.bar";

        String image = document.select("meta[property=og:image]")
                .attr("content");

        int i = image.indexOf("http");

        if (i == -1){

        }else if(image.indexOf("http", i + 4) != -1){
            image = image.replace(http, "");
        }

        String author = document.select("meta[property=og:novel:author]")
                .attr("content");

        FictionClass fictionClass = fictionClassService.
                lambdaQuery().eq(FictionClass::getFictionClassName, fictionClassName).one();

        if (fictionClass == null){
            fictionClass = new FictionClass();
            fictionClass.setFictionClassName(fictionClassName);
            fictionClassService.save(fictionClass);
        }

        Fiction fiction = new Fiction();
        fiction.setFictionLabel(fictionClassName);
        fiction.setImage(image);
        fiction.setFictionClassId(fictionClass.getFictionClassId());
        fiction.setStatus("连载".equals(status) ? 0 : 1);
        fiction.setFictionAuthor(author);
        fiction.setFictionName(name);
        fiction.setFictionInfo(description);
        fiction.setFictionLink(url);
        //if (num.indexOf("万")  != -1){
        //    fiction.setWordNum((int) (Double.valueOf(num.replace("万", "")) * 10000));
        //}else {
        //    fiction.setWordNum(Integer.valueOf(num));
        //}

        Date date = null;
        try {
            date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(updateTime);
        }catch (Exception eee){}

        fiction.setUpdateTime(date);

        return fiction;
    }

    public List<FictionChapter> DocumentToObjectFictionChapter(Document document, int fid) {

        Elements ddA = document.select(".section-box .section-list");

        if (ddA.size() == 2) {
            ddA = ddA.get(1).select(".book-item a");
        }else if (ddA.size() == 1){
            ddA = ddA.get(0).select(".book-item a");
        }

        ArrayList<FictionChapter> fictionChapters = new ArrayList<>();
        boolean is = true;

        int j = 0;

        if (ddA == null){
            return fictionChapters;
        }

        for (int i = 0; i < ddA.size(); i++) {
            Element element = ddA.get(i);
            String name = element.text()
                    .replace("全部章节_", "")
                    .replace("章节目录", "");

//            if (!is){
//                if (isChapterI(name)){
//                    is = true;
//                }
//            }
            if (is)  {
                FictionChapter fictionChapter = new FictionChapter();
                fictionChapter.setChapterNum(j);
                fictionChapter.setFictionId(fid);
                fictionChapter.setChapterLink(element.attr("href"));
                fictionChapter.setChapterName(name);
                fictionChapters.add(fictionChapter);
                j++;
            }
        }

        return fictionChapters;
    }

    public List<String> DocumentToStringListFictionContent(Document document, int id){
        String[] split = document.select("#content").toString()
                .replace("<div class=\"posterror\">\n" +
                        "  <a href=\"javascript:postError();\" class=\"red\">章节错误,点此举报(免注册)</a>,举报后维护人员会在两分钟内校正章节内容,请耐心等待,并刷新页面。", "")
                .replaceAll("<div class=\"content\" id=\"content\">", "")
                .replaceAll("</div>", "")
                .replaceAll("\n", "")
                .replaceAll("&nbsp;", "")
                .split("<br>");

        List<String> strings = Arrays.asList(split);
        String s = null;

        for (Element element : document.select(".section-opt a")) {
            if ("下一页".equals(element.text())){
                s = element.attr("href");
            }
        }

        if (s != null){
            List<String> strings1 = DocumentToStringListFictionContent(JsoupBooksUtil.getDoc(baseUrl + s), id);
            strings = Stream.of(strings, strings1).flatMap(Collection::stream).collect(Collectors.toList());
        }

        return strings;
    }

    public FictionContent DocumentToObjectFictionContent(Document document, int id) {

        FictionContent fictionContents = new FictionContent();

        List<String> strings = DocumentToStringListFictionContent(document, id);

        fictionContents.setContent(JSONObject.toJSONString(strings));

        fictionContents.setFictionChapterId(id);

        strings.forEach(n -> {
            fictionContents.setNum(fictionContents.getNum() + n.length());
        });

        return fictionContents;
    }
}
